package com.example.sxt_practise.thread;

import java.util.concurrent.TimeUnit;

/**
 * 可重入锁
 * @author gaofeng
 * @date 2022年06月04日 20:16
 */
public class SynchronizedTest {
    public static void main(String[] args) {
        SynchronizedTest synchronizedTest = new SynchronizedTest() ;
        for (int i = 0; i < 3; i++) {
            int finalI = i;
            new Thread(() -> {
                System.out.println("用户" + finalI + "开始下订单");
                synchronizedTest.operation();
            }).start();
        }
    }

    int count = 100 ;
    public synchronized void operation() {
        System.out.println("第一层锁:减库存");
        count -- ;
        add() ;
        System.out.println("下订单结束,库存剩余:" + count);
    }

    private synchronized void add() {
        System.out.println("第二层锁:插入订单");
        try {
            TimeUnit.SECONDS.sleep(10);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}
